package com.stox.core.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import com.stox.core.dao.mapper.ExchangeRowMapper;
import com.stox.core.model.Exchange;
import com.stox.core.model.exception.StoxException;
import com.stox.design.DatabaseConfigurer;
import com.stox.ioc.Container;

public class ExchangeDao extends AbstractDao implements DatabaseConfigurer{

	private ExchangeRowMapper exchangeRowMapper;
	
	public ExchangeDao() {
		this.exchangeRowMapper = Container.get(ExchangeRowMapper.class);
	}
	
	@Override
	public int getOrder() {
		return 0;
	}
	
	@Override
	public Object invoke(List<String> payload) {
		if(!payload.contains("EXCHANGE")){
			try {
				getConnection().createStatement().execute(ExchangeRowMapper.createSql);
				commit();
			} catch (SQLException e) {
				throw new StoxException(e);
			}
		}
		return null;
	}
	
	public void updateLastTradingDate(String code, Date date) throws SQLException{
		String sql = "update exchange set lastTradingDate = ? where code = ?";
		PreparedStatement ps = getConnection().prepareStatement(sql);
		ps.setDate(1, new java.sql.Date(date.getTime()));
		ps.setString(2, code);
		ps.executeUpdate();
	}
	
	public void updateConfigured(String exchangeCode, boolean value) throws SQLException{
		String sql = "update exchange set configured = ? where code = ?";
		PreparedStatement ps = getConnection().prepareStatement(sql);
		ps.setBoolean(1,value);
		ps.setString(2, exchangeCode);
		ps.executeUpdate();
	}
	
	public void updateFirstTimeDownloadCompleted(String exchangeCode, boolean value) throws SQLException{
		String sql = "update exchange set ftdc = ? where code = ?";
		PreparedStatement ps = getConnection().prepareStatement(sql);
		ps.setBoolean(1,value);
		ps.setString(2, exchangeCode);
		ps.executeUpdate();
	}
	
	public List<Exchange> get() throws SQLException{
		return exchangeRowMapper.map(
				getConnection().createStatement().executeQuery(ExchangeRowMapper.selectSql));
	}
	
	public void persist(Exchange exchange) throws SQLException{
		PreparedStatement ps = getConnection().prepareStatement(ExchangeRowMapper.insertSql);
		exchangeRowMapper.map(ps, exchange);
		ps.execute();
	}
}
